﻿using CollectionCreator.Classes;
using CollectionCreator.Windows;
using Microsoft.ConfigurationManagement.ManagementProvider;
using Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Management;

namespace CollectionCreator
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        public WqlConnectionManager WMIConnection;
        public ObservableCollection<CMApplications> Applications = new ObservableCollection<CMApplications>();
        public ObservableCollection<CMGroups> Groups = new ObservableCollection<CMGroups>();
        ConfigMgr CM = new ConfigMgr();
        CMApplications CMApps = new CMApplications();
        CMCollections CMCols = new CMCollections();
        CMGroups CMGroups = new CMGroups();

        public MainWindow()
        {
            InitializeComponent();

        }


        // Closes the Application
        void Exit(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        // Shows About Window
        void ShowAbout(object sender, RoutedEventArgs e)
        {
            About WS = new About();
            WS.ShowInTaskbar = false;

            if (WS.ShowDialog() == false)
            {

            }
        }

        //
        void AppOrProduct(object sender, RoutedEventArgs e)
        {
            if (App_UseName.IsChecked == true)
            {

                //make a new source

                Binding b = new Binding();
                b.Source = Appene;
                b.Path = new PropertyPath("SelectedItem.Name");
                b.Mode = BindingMode.OneWay;
                AppName.SetBinding(TextBox.TextProperty, b);

            }
            else
            {

                //make a new source

                Binding b = new Binding();
                b.Source = Appene;
                b.Path = new PropertyPath("SelectedItem.ProductCode");
                b.Mode = BindingMode.OneWay;
                AppName.SetBinding(TextBox.TextProperty, b);

            }
        }

        // Clicked on Connect -> Tries to connect to SCCM Provider.
        private void BT_Connect_Click(object sender, RoutedEventArgs e)
        {

            string server = CMServer.Text;
            string username = CMUser.Text;
            string password = CMPass.Text;

            try 
            {
                WMIConnection = CM.connect(server, username, password);
                BT_Connect.IsEnabled = false;
                BT_Connect.Content = "Connected";
            }
            catch(SmsException ex)
            {
                MessageBox.Show(ex.Message);
            }


        }

        
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (WMIConnection != null)
            {
                

                try
                {
                    string search = txt_search.Text;
                    ObservableCollection<CMApplications> apps = CMApps.GetAll(WMIConnection, search);

                    Applications = apps;
                    Appene.ItemsSource = Applications;
                }
                catch (SmsException ex)
                {
                    MessageBox.Show(ex.Message);
                }
                    //MessageBox.Show(ex);
                

            }
        }

        private void btn_FindCollections_Click(object sender, RoutedEventArgs e)
        {

            string search = AppColSearch.Text;

            if (WMIConnection != null)
            {
                try
                {
                    ObservableCollection<CMCollections> col = CMCols.Get(WMIConnection, search, "2");
                    AppCol.ItemsSource = col;
                }
                catch(SmsException ex)
                {
                    MessageBox.Show(ex.Message);
                }
                
            }

        }

        private void App_Create_Click(object sender, RoutedEventArgs e)
        {

            string ApplicationName = AppName.Text;
            string newCollectionComment = AppComment.Text;
            bool ownedByThisSite = false;
            string queryname = AppQueryName.Text;
            string ver = AppVersion.Text;
            string newCollectionName = AppColName.Text;
            string checkif = "";
            string colquery = "";
            string appoperator = "";
            string veroperator = "";
            int coltype = 2;
            int refreshtype = 0;

            IResultObject result;

            //Checks for required items.
            if (string.IsNullOrEmpty(ApplicationName) || string.IsNullOrWhiteSpace(ApplicationName))
            {
                MessageBox.Show("Missing \"Check for\" ! ");
                return;
            }

            if (string.IsNullOrEmpty(queryname) || string.IsNullOrWhiteSpace(queryname))
            {
                MessageBox.Show("Missing \"QueryName\" ! ");
                return;
            }

            if (string.IsNullOrEmpty(newCollectionName) || string.IsNullOrWhiteSpace(newCollectionName))
            {
                MessageBox.Show("Missing \"CollectionName\" ! ");
                return;
            }


            string limit;
            if (AppCol.SelectedItems.Count != 0)
            {
                var Limit = AppCol.SelectedItems[0] as CMCollections;
                limit = Limit.Id;
            }
            else
            {
                MessageBox.Show("Missing \"Limit Collection\" ! ");
                return;
            }


            // Sets Update
            if (AppSchedInc.IsChecked == true)
            {
                //Incremental = 4
                refreshtype = refreshtype + 4;
            }
            if (AppSchedSch.IsChecked == true)
            {
                //Schedule = 2
                refreshtype = refreshtype + 2;
            }



            if (WMIConnection != null)
            {

                try
                {
                    result = CMCols.Create(WMIConnection, newCollectionName, newCollectionComment, ownedByThisSite, limit, coltype, refreshtype);
                
                    //Add Schedule
                    // Generate Schedule token and add schedule to Collection.
                    List<IResultObject> tempScheduleTokenArray = new List<IResultObject>();
                    // Create and populate a temporary schedule token object with the new schedule value.
                    IResultObject tempScheduleTokenObject = CM.CreateRecurringScheduleToken(WMIConnection, 4, 7, ManagementDateTimeConverter.ToDmtfDateTime(DateTime.Now), false, 1, 2, 3, 5);
                    // Add the newly created schedule token object to the local array list.
                    tempScheduleTokenArray.Add(tempScheduleTokenObject);
                    result.SetArrayItems("RefreshSchedule", tempScheduleTokenArray);
                    result.Put();



                    //QUERIES
                    string colquery_both = "select SMS_R_System.ResourceId, SMS_R_System.ResourceType, SMS_R_System.Name, SMS_R_System.SMSUniqueIdentifier, SMS_R_System.ResourceDomainORWorkgroup, SMS_R_System.Client from  SMS_R_System inner join SMS_G_System_ADD_REMOVE_PROGRAMS on SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID = SMS_R_System.ResourceId where SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID {CHECKIF} (select SMS_R_SYSTEM.ResourceID from SMS_R_System inner join SMS_G_System_ADD_REMOVE_PROGRAMS on SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID = SMS_R_System.ResourceId inner join SMS_G_System_ADD_REMOVE_PROGRAMS_64 on SMS_G_System_ADD_REMOVE_PROGRAMS_64.ResourceId = SMS_R_System.ResourceId where (SMS_G_System_ADD_REMOVE_PROGRAMS.DisplayName {OPERATORAPP} \"{APP}\" or SMS_G_System_ADD_REMOVE_PROGRAMS_64.DisplayName {OPERATORAPP} \"{APP}\") and (SMS_G_System_ADD_REMOVE_PROGRAMS.Version {OPERATORVER} \"{VER}\" or SMS_G_System_ADD_REMOVE_PROGRAMS_64.Version {OPERATORVER} \"{VER}\"))";
                    string colquery_x64 = "select SMS_R_System.ResourceId, SMS_R_System.ResourceType, SMS_R_System.Name, SMS_R_System.SMSUniqueIdentifier, SMS_R_System.ResourceDomainORWorkgroup, SMS_R_System.Client from  SMS_R_System inner join SMS_G_System_ADD_REMOVE_PROGRAMS on SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID = SMS_R_System.ResourceId where SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID {CHECKIF} (select SMS_R_SYSTEM.ResourceID from SMS_R_System inner join SMS_G_System_ADD_REMOVE_PROGRAMS_64 on SMS_G_System_ADD_REMOVE_PROGRAMS_64.ResourceId = SMS_R_System.ResourceId where (SMS_G_System_ADD_REMOVE_PROGRAMS_64.DisplayName {OPERATORAPP} \"{APP}\") and (SMS_G_System_ADD_REMOVE_PROGRAMS_64.Version {OPERATORVER} \"{VER}\"))";
                    string colquery_x86 = "select SMS_R_System.ResourceId, SMS_R_System.ResourceType, SMS_R_System.Name, SMS_R_System.SMSUniqueIdentifier, SMS_R_System.ResourceDomainORWorkgroup, SMS_R_System.Client from  SMS_R_System inner join SMS_G_System_ADD_REMOVE_PROGRAMS on SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID = SMS_R_System.ResourceId where SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID {CHECKIF} (select SMS_R_SYSTEM.ResourceID from SMS_R_System inner join SMS_G_System_ADD_REMOVE_PROGRAMS on SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID = SMS_R_System.ResourceId where (SMS_G_System_ADD_REMOVE_PROGRAMS.DisplayName {OPERATORAPP} \"{APP}\") and (SMS_G_System_ADD_REMOVE_PROGRAMS.Version {OPERATORVER} \"{VER}\"))";

                    //Needs to be fixed
                    string colquery_ID_both = "select SMS_R_System.ResourceId, SMS_R_System.ResourceType, SMS_R_System.Name, SMS_R_System.SMSUniqueIdentifier, SMS_R_System.ResourceDomainORWorkgroup, SMS_R_System.Client from  SMS_R_System inner join SMS_G_System_ADD_REMOVE_PROGRAMS on SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID = SMS_R_System.ResourceId where SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID {CHECKIF} (select SMS_R_SYSTEM.ResourceID from SMS_R_System inner join SMS_G_System_ADD_REMOVE_PROGRAMS on SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID = SMS_R_System.ResourceId inner join SMS_G_System_ADD_REMOVE_PROGRAMS_64 on SMS_G_System_ADD_REMOVE_PROGRAMS_64.ResourceId = SMS_R_System.ResourceId where (SMS_G_System_ADD_REMOVE_PROGRAMS.ProdID {OPERATORAPP} \"{APPID}\" or SMS_G_System_ADD_REMOVE_PROGRAMS_64.ProdID {OPERATORAPP} \"{APPID}\") and (SMS_G_System_ADD_REMOVE_PROGRAMS.Version {OPERATORVER} \"{VER}\" or SMS_G_System_ADD_REMOVE_PROGRAMS_64.Version {OPERATORVER} \"{VER}\"))";
                    string colquery_ID_x64 = "select SMS_R_System.ResourceId, SMS_R_System.ResourceType, SMS_R_System.Name, SMS_R_System.SMSUniqueIdentifier, SMS_R_System.ResourceDomainORWorkgroup, SMS_R_System.Client from  SMS_R_System inner join SMS_G_System_ADD_REMOVE_PROGRAMS on SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID = SMS_R_System.ResourceId where SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID {CHECKIF} (select SMS_R_SYSTEM.ResourceID from SMS_R_System inner join SMS_G_System_ADD_REMOVE_PROGRAMS_64 on SMS_G_System_ADD_REMOVE_PROGRAMS_64.ResourceId = SMS_R_System.ResourceId where (SMS_G_System_ADD_REMOVE_PROGRAMS_64.ProdID {OPERATORAPP} \"{APPID}\") and (SMS_G_System_ADD_REMOVE_PROGRAMS_64.Version {OPERATORVER} \"{VER}\"))";
                    string colquery_ID_x86 = "select SMS_R_System.ResourceId, SMS_R_System.ResourceType, SMS_R_System.Name, SMS_R_System.SMSUniqueIdentifier, SMS_R_System.ResourceDomainORWorkgroup, SMS_R_System.Client from  SMS_R_System inner join SMS_G_System_ADD_REMOVE_PROGRAMS on SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID = SMS_R_System.ResourceId where SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID {CHECKIF} (select SMS_R_SYSTEM.ResourceID from SMS_R_System inner join SMS_G_System_ADD_REMOVE_PROGRAMS on SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID = SMS_R_System.ResourceId where (SMS_G_System_ADD_REMOVE_PROGRAMS.ProdID {OPERATORAPP} \"{APPID}\") and (SMS_G_System_ADD_REMOVE_PROGRAMS.Version {OPERATORVER} \"{VER}\"))";


                    string colquery_both_noVer = "select SMS_R_System.ResourceId, SMS_R_System.ResourceType, SMS_R_System.Name, SMS_R_System.SMSUniqueIdentifier, SMS_R_System.ResourceDomainORWorkgroup, SMS_R_System.Client from  SMS_R_System inner join SMS_G_System_ADD_REMOVE_PROGRAMS on SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID = SMS_R_System.ResourceId where SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID {CHECKIF} (select SMS_R_SYSTEM.ResourceID from SMS_R_System inner join SMS_G_System_ADD_REMOVE_PROGRAMS on SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID = SMS_R_System.ResourceId inner join SMS_G_System_ADD_REMOVE_PROGRAMS_64 on SMS_G_System_ADD_REMOVE_PROGRAMS_64.ResourceId = SMS_R_System.ResourceId where (SMS_G_System_ADD_REMOVE_PROGRAMS.DisplayName {OPERATORAPP} \"{APP}\" or SMS_G_System_ADD_REMOVE_PROGRAMS_64.DisplayName {OPERATORAPP} \"{APP}\"))";
                    string colquery_x64_noVer = "select SMS_R_System.ResourceId, SMS_R_System.ResourceType, SMS_R_System.Name, SMS_R_System.SMSUniqueIdentifier, SMS_R_System.ResourceDomainORWorkgroup, SMS_R_System.Client from  SMS_R_System inner join SMS_G_System_ADD_REMOVE_PROGRAMS on SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID = SMS_R_System.ResourceId where SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID {CHECKIF} (select SMS_R_SYSTEM.ResourceID from SMS_R_System inner join SMS_G_System_ADD_REMOVE_PROGRAMS_64 on SMS_G_System_ADD_REMOVE_PROGRAMS_64.ResourceId = SMS_R_System.ResourceId where (SMS_G_System_ADD_REMOVE_PROGRAMS_64.DisplayName {OPERATORAPP} \"{APP}\"))";
                    string colquery_x86_noVer = "select SMS_R_System.ResourceId, SMS_R_System.ResourceType, SMS_R_System.Name, SMS_R_System.SMSUniqueIdentifier, SMS_R_System.ResourceDomainORWorkgroup, SMS_R_System.Client from  SMS_R_System inner join SMS_G_System_ADD_REMOVE_PROGRAMS on SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID = SMS_R_System.ResourceId where SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID {CHECKIF} (select SMS_R_SYSTEM.ResourceID from SMS_R_System inner join SMS_G_System_ADD_REMOVE_PROGRAMS on SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID = SMS_R_System.ResourceId where (SMS_G_System_ADD_REMOVE_PROGRAMS.DisplayName {OPERATORAPP} \"{APP}\"))";

                    //Needs to be fixed
                    string colquery_ID_both_noVer = "select SMS_R_System.ResourceId, SMS_R_System.ResourceType, SMS_R_System.Name, SMS_R_System.SMSUniqueIdentifier, SMS_R_System.ResourceDomainORWorkgroup, SMS_R_System.Client from  SMS_R_System inner join SMS_G_System_ADD_REMOVE_PROGRAMS on SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID = SMS_R_System.ResourceId where SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID {CHECKIF} (select SMS_R_SYSTEM.ResourceID from SMS_R_System inner join SMS_G_System_ADD_REMOVE_PROGRAMS on SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID = SMS_R_System.ResourceId inner join SMS_G_System_ADD_REMOVE_PROGRAMS_64 on SMS_G_System_ADD_REMOVE_PROGRAMS_64.ResourceId = SMS_R_System.ResourceId where (SMS_G_System_ADD_REMOVE_PROGRAMS.ProdID {OPERATORAPP} \"{APPID}\" or SMS_G_System_ADD_REMOVE_PROGRAMS_64.ProdID {OPERATORAPP} \"{APPID}\"))";
                    string colquery_ID_x64_noVer = "select SMS_R_System.ResourceId, SMS_R_System.ResourceType, SMS_R_System.Name, SMS_R_System.SMSUniqueIdentifier, SMS_R_System.ResourceDomainORWorkgroup, SMS_R_System.Client from  SMS_R_System inner join SMS_G_System_ADD_REMOVE_PROGRAMS on SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID = SMS_R_System.ResourceId where SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID {CHECKIF} (select SMS_R_SYSTEM.ResourceID from SMS_R_System inner join SMS_G_System_ADD_REMOVE_PROGRAMS_64 on SMS_G_System_ADD_REMOVE_PROGRAMS_64.ResourceId = SMS_R_System.ResourceId where (SMS_G_System_ADD_REMOVE_PROGRAMS_64.ProdID {OPERATORAPP} \"{APPID}\"))";
                    string colquery_ID_x86_noVer = "select SMS_R_System.ResourceId, SMS_R_System.ResourceType, SMS_R_System.Name, SMS_R_System.SMSUniqueIdentifier, SMS_R_System.ResourceDomainORWorkgroup, SMS_R_System.Client from  SMS_R_System inner join SMS_G_System_ADD_REMOVE_PROGRAMS on SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID = SMS_R_System.ResourceId where SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID {CHECKIF} (select SMS_R_SYSTEM.ResourceID from SMS_R_System inner join SMS_G_System_ADD_REMOVE_PROGRAMS on SMS_G_System_ADD_REMOVE_PROGRAMS.ResourceID = SMS_R_System.ResourceId where (SMS_G_System_ADD_REMOVE_PROGRAMS.ProdID {OPERATORAPP} \"{APPID}\"))";



                    //x86
                    if (App_x86.IsChecked == true)
                    {

                        if (string.IsNullOrEmpty(ver) == false && appver_check.IsChecked == true)
                        {

                            if (App_UseName.IsChecked == true)
                            {
                                colquery = colquery_x86;
                            }
                            else
                            {
                                colquery = colquery_ID_x86;
                            }
                        }
                        else
                        {

                            if (App_UseName.IsChecked == true)
                            {
                                colquery = colquery_x86_noVer;
                            }
                            else
                            {
                                colquery = colquery_ID_x86_noVer;
                            }
                        }

                    }
                    //x64
                    else if (App_x64.IsChecked == true)
                    {

                        if (string.IsNullOrEmpty(ver) == false && appver_check.IsChecked == true)
                        {

                            if (App_UseName.IsChecked == true)
                            {
                                colquery = colquery_x64;
                            }
                            else
                            {
                                colquery = colquery_ID_x64;
                            }
                        }
                        else
                        {

                            if (App_UseName.IsChecked == true)
                            {
                                colquery = colquery_x64_noVer;
                            }
                            else
                            {
                                colquery = colquery_ID_x64_noVer;
                            }

                        }
                    }
                    //both
                    else if (App_Both.IsChecked == true)
                    {

                        if (string.IsNullOrEmpty(ver) == false && appver_check.IsChecked == true)
                        {

                            if (App_UseName.IsChecked == true)
                            {
                                colquery = colquery_both;
                            }
                            else
                            {
                                colquery = colquery_ID_both;
                            }
                        }
                        else
                        {

                            if (App_UseName.IsChecked == true)
                            {
                                colquery = colquery_both_noVer;
                            }
                            else
                            {
                                colquery = colquery_ID_both_noVer;
                            }
                        }
                    }


                    //Checkfor (is in)
                    if (App_Inst.IsChecked == true)
                    {

                        checkif = "is in";

                    }
                    //Checkfor is not in
                    else if (App_NotInst.IsChecked == true)
                    {

                        checkif = "is not in";

                    }

                    //operator app =
                    if (Oper_AppName.Text == "equal")
                    {

                        appoperator = "=";

                    }
                    //operator app
                    else if (Oper_AppName.Text == "like")
                    {

                        appoperator = "like";

                    }


                    //operator ver =
                    if (Oper_AppVer.Text == "equal")
                    {

                        veroperator = "=";

                    }
                    //operator ver
                    else if (Oper_AppVer.Text == "like")
                    {

                        veroperator = "like";
                    }

                    if (App_UseName.IsChecked == true)
                    {
                        colquery = colquery.Replace("{APP}", ApplicationName);
                    }
                    else
                    {
                        colquery = colquery.Replace("{APPID}", ApplicationName);
                    }


                    colquery = colquery.Replace("{VER}", ver);
                    colquery = colquery.Replace("{OPERATORAPP}", appoperator);
                    colquery = colquery.Replace("{OPERATORVER}", veroperator);
                    colquery = colquery.Replace("{CHECKIF}", checkif);



                    try
                    {
                        CMCols.AddQuery(WMIConnection, result, colquery, queryname);
                        MessageBox.Show("Created: " + result["name"].StringValue);
                    }
                    catch(SmsException ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    
                    
                }
                catch(SmsException ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }



        }

        private void btn_FindGroupCol_Click(object sender, RoutedEventArgs e)
        {

            string search = SearchColl.Text;

            if (WMIConnection != null)
            {
                try
                {
                    ObservableCollection<CMCollections> col = CMCols.Get(WMIConnection, search);
                    GroupCol.ItemsSource = col;
                }
                catch (SmsException ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }

        }

        private void btn_GroupSearch_Click(object sender, RoutedEventArgs e)
        {
            if (WMIConnection != null)
            {


                try
                {
                    string search = GroupSearch.Text;
                    ObservableCollection<CMGroups> groups = CMGroups.Get(WMIConnection, search);

                    Groups = groups;
                    lst_Groups.ItemsSource = Groups;
                }
                catch (SmsException ex)
                {
                    MessageBox.Show(ex.Message);
                }
                //MessageBox.Show(ex);


            }
        }

        private void Group_Create_Click(object sender, RoutedEventArgs e)
        {

            
            bool ownedByThisSite = false;
            string newCollectionName = GroupCollName.Text;
            string newCollectionComment = GroupComment.Text;
            string queryname = GroupQueryName.Text;
            string groupname = txt_Group.Text;

            int coltype;
            int refreshtype = 0;

            string limit;
            if (GroupCol.SelectedItems.Count != 0)
            {
                var Limit = GroupCol.SelectedItems[0] as CMCollections;
                limit = Limit.Id;
                coltype = Convert.ToInt32(Limit.Type);
            }
            else
            {
                MessageBox.Show("Missing \"Limit Collection\" ! ");
                return;
            }


            // Sets Update
            if (GrpSchedInc.IsChecked == true)
            {
                //Incremental = 4
                refreshtype = refreshtype + 4;
            }
            if (GrpSchedSch.IsChecked == true)
            {
                //Schedule = 2
                refreshtype = refreshtype + 2;
            }


            IResultObject result = CMCols.Create(WMIConnection, newCollectionName, newCollectionComment, ownedByThisSite, limit, coltype, refreshtype);

            
            //Add Schedule
            // Generate Schedule token and add schedule to Collection.
            List<IResultObject> tempScheduleTokenArray = new List<IResultObject>();
            // Create and populate a temporary schedule token object with the new schedule value.
            IResultObject tempScheduleTokenObject = CM.CreateRecurringScheduleToken(WMIConnection, 4, 7, ManagementDateTimeConverter.ToDmtfDateTime(DateTime.Now), false, 1, 2, 3, 5);
            // Add the newly created schedule token object to the local array list.
            tempScheduleTokenArray.Add(tempScheduleTokenObject);
            result.SetArrayItems("RefreshSchedule", tempScheduleTokenArray);
            result.Put();

            // select *  from  SMS_R_User where SMS_R_User.UserGroupName = "VIAMONSTRA\\Domain Admins"

            string colquery;

            if (coltype == 1)
            {
                 colquery = "select * from SMS_R_User where SMS_R_User.UserGroupName = \"" + groupname + "\"";
                
            }
            else if (coltype == 2)
            {
                // select *  from  SMS_R_System where SMS_R_System.SystemGroupName = "VIAMONSTRA\\Domain Computers"
                colquery = "select *  from  SMS_R_System where SMS_R_System.SystemGroupName = \"" + groupname + "\"";
                
            }
            else
            {
                return;
            }


            colquery = colquery.Replace(@"\",@"\\");
            
            try
            {
                CMCols.AddQuery(WMIConnection, result, colquery, queryname);
                MessageBox.Show("Created: " + result["name"].StringValue);
            }
            catch (SmsException ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

    }
}
